package com.example.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.reggie.common.R;
import com.example.reggie.domain.User;
import com.example.reggie.service.UserService;
import com.example.reggie.util.SMSUtils;
import com.example.reggie.util.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController extends BaseController {
    @Autowired
    private UserService userService;

    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user) {
        String phone = user.getPhone();
        if (StringUtils.isNotEmpty(phone)) {
            String code = ValidateCodeUtils.generateValidateCode(6).toString();
            log.info("code: {}", code);
            SMSUtils.sendMessage("reggie", "test", phone, code);
//            SMSUtils.sendMessage("reggie", "SMS_461405088", phone, code);
            session.setAttribute(phone, code);
            return R.success("发送成功！");

        }
        return R.error("短信发送失败！");
    }

    @PostMapping("/login")
    public R<User> login(@RequestBody Map map) {

        String phone = map.get("phone").toString();
        String code = map.get("code").toString();

        String codeInSession = session.getAttribute(phone).toString();
        if (codeInSession != null && codeInSession.equals(code)) {
            LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userLambdaQueryWrapper.eq(User::getPhone, phone);
            User user = userService.getOne(userLambdaQueryWrapper);
            if (ObjectUtils.isEmpty(user)) {
                User newUser = new User();
                newUser.setPhone(phone);
                userService.save(newUser);
                session.setAttribute("user", newUser.getId());
                return R.success(newUser);
            }
            session.setAttribute("user", user.getId());
            return R.success(user);
        }

        return R.error("登陆失败！");
    }

    @PostMapping("/loginout")
    public R<String> loginOut(){
        session.removeAttribute("user");
        return R.success("退出登录成功！");
    }
}
